package ar.com.ford.it.fullEconomics.view.action;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.FullEconomicsFacade;
import ar.com.ford.it.fullEconomics.facade.VehiclelinFacade;
import ar.com.ford.it.fullEconomics.persistence.dao.FullEconomicsDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas012VehicleVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc02Coststvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc03Subcoststr;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc07Subcstitem;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese05Paypolvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesf01Fulleconom;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesf02Fullecoitm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp06Mix;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.FullEconomicWrapStruct;
import ar.com.ford.it.fullEconomics.struct.FullEconomicsStruct;
import ar.com.ford.it.fullEconomics.struct.MacropartStruct;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.CostStructureDefForm;
import ar.com.ford.it.fullEconomics.view.form.FullEconomicsForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;
import com.ford.it.persistence.PersistenceException;

public class FullEconomicsAction extends AbstractBaseAction {

    private Collection getEvolveTypeCombo(FullEconomicsWslxUser user,
                                          HttpServletRequest request) {
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        Collection<OptionCombo> ecoType = new ArrayList<OptionCombo>();
        OptionCombo actual = new OptionCombo("A", resources
                .getMessage("economicValue.label.actual"));
        ecoType.add(actual);
        OptionCombo forcasted = new OptionCombo("F", resources
                .getMessage("economicValue.label.forescated"));
        if (user.getPermissions().contains("PERM_F")) {
            ecoType.add(forcasted);
        }
        return ecoType;
    }

    /**
     * metodo que devuelve una coleccion de fulleconitms llamando al metodo
     * recursivo para obtener todos los items de un full economic
     * 
     * @param form
     * @param facade
     * @return
     * @throws FullEconomicsException
     */
    private Collection<Teesf02Fullecoitm> getFullEconColForCreate(
                                                                  FullEconomicsForm form,
                                                                  HttpServletRequest request)
            throws FullEconomicsException {

        VehiclelinFacade vehicleLineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);
        Ncas012VehicleVw vehicleLine = new Ncas012VehicleVw();
        vehicleLine.setCas012VehicleCodeC(form.getVehicleLineSel());
        vehicleLine = vehicleLineFacade.findVehicleLineByPk(vehicleLine);
        Teesf01Fulleconom fullEconomic = new Teesf01Fulleconom();
        Collection<Teesf02Fullecoitm> fullEconItemCol = new LinkedList<Teesf02Fullecoitm>();
        Collection<FullEconomicsStruct> fullEconStructCol = null;
        fullEconomic.setEesf01FulleCommentsX(form.getComments());
        fullEconomic.setEesf01FulleEcolevel1DateY(form.getEconLevel1());
        fullEconomic.setEesf01FulleEcolevel2DateY(form.getEconLevel2());
        fullEconomic.setTeesc02Coststvers(form.getCostStrVersion());
        fullEconomic.setNcas012VehicleVw(vehicleLine);
        fullEconomic.setEesf01FulleAmountA(form.getTotals().getFeTotal());
        fullEconomic.setEesf01FullePaypolAmountA(form.getTotals().getPpTotal());
        Iterator<String> altValueIt = form.getAltValue2Coll().iterator();
        Iterator<FullEconomicsStruct> fullEconIt = form
                .getColFullEconomicsStruct().iterator();
        while (altValueIt.hasNext()) {
            fullEconIt.next().setAltValue(new BigDecimal(altValueIt.next()));
        }
        String mixMonth = Integer.parseInt(form.getMixDate()) < 10 ? "0"
                + form.getMixDate() : form.getMixDate();
        String strMixDate = "01/" + mixMonth + "/" + form.getMixYear();
        Timestamp mixDate = new Timestamp(FullEconomicsDateUtil.format(
                strMixDate).getTimeInMillis());
        fullEconomic.setEesf01MixEffectiveDateY(mixDate);
        // llamo a la funcion recursiva para buscar todos los items tando de
        // este fulle como de los subFulle
        fullEconStructCol = this.getAllFullEconStructs(form
                .getColFullEconomicsStruct(),
                new LinkedList<FullEconomicsStruct>(), form.getCostStrVersion()
                        .getTeesc01Coststruct().getTeess01Supplier(), form
                        .getEconLevel1(), form.getEconLevel1Forecasted(), form
                        .getEconLevel2(), form.getEconLevel2Forecasted());
        for (FullEconomicsStruct row : fullEconStructCol) {
            if (row.getSubCostStrItem() != null) {
                Teesf02Fullecoitm fullEconItem = new Teesf02Fullecoitm();
                
                fullEconItem.setEesf02FulleEcolevel1DateY(FullEconomicsDateUtil.formatFromCombo(row.getSubCostStrItem().getEvolveFromTempKey(), row.getSubCostStrItem().getEvolveFromYearTemp()));
                fullEconItem.setEesf02FulleEcolevel2DateY(FullEconomicsDateUtil.formatFromCombo(row.getSubCostStrItem().getEvolveToTempKey(), row.getSubCostStrItem().getEvolveToYearTemp()));
                
                fullEconItem.setTeesf01Fulleconom(fullEconomic);
                if (row.getEconValue1() != null) {
                    fullEconItem.setEesf02FeitmValue1AmountA(row
                            .getEconValue1().getEese03EcvalueAmountA());
                    fullEconItem.setEesf02FeitmValue1TypeCodeC(form
                            .getEconLevel1Forecasted());
                }
                if (row.getEconValue2() != null) {
                    fullEconItem.setEesf02FeitmValue2AmountA(row
                            .getEconValue2().getEese03EcvalueAmountA());
                    fullEconItem.setEesf02FeitmValue2TypeCodeC(form
                            .getEconLevel2Forecasted());
                }
                if (row.getSubCostStrItem().getTeese01Economic() != null)
                    fullEconItem.setTeese01Economic(row.getSubCostStrItem()
                            .getTeese01Economic());
                fullEconItem.setTeesc07Subcstitem(row.getSubCostStrItem());
                fullEconItem.setTeese05Paypolvers(row.getPayPolVers());
                fullEconItem.setEesf02FeitmValue2tAmountA(row.getAltValue());
                if (row.getPayPolVers() != null)
                    fullEconItem.setEesf02PaypolPercentP(row.getPayPolVers()
                            .getEese05PpyverPercentP());
                fullEconItemCol.add(fullEconItem);
            }
        }
        return fullEconItemCol;
    }

    /**
     * Metodo recursivo para obtener todos los items de un full economic
     * contenidos en FullEconomicsStructs
     * 
     * @param father
     * @param result
     * @param supplier
     * @param econLevel1
     * @param econLevel1Forecasted
     * @param econLevel2
     * @param econLevel2Forecasted
     * @param facade
     * @return
     * @throws FullEconomicsException
     */
    private Collection<FullEconomicsStruct> getAllFullEconStructs(
                                                                  Collection<FullEconomicsStruct> father,
                                                                  Collection<FullEconomicsStruct> result,
                                                                  Teess01Supplier supplier,
                                                                  Timestamp econLevel1,
                                                                  String econLevel1Forecasted,
                                                                  Timestamp econLevel2,
                                                                  String econLevel2Forecasted)
            throws FullEconomicsException {

        for (FullEconomicsStruct row : father) {
            if (row.getSubCostStrItem() == null) {
                this.getAllFullEconStructs(row.getSubStructs(), result,
                        supplier, econLevel1, econLevel1Forecasted, econLevel2,
                        econLevel2Forecasted);
            } else
                result.add(row);
        }
        return result;
    }

    /**
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        FullEconomicsFacade fullEconomicsFacade = (FullEconomicsFacade) FacadeProvider.getFacade(request, FullEconomicsFacade.class);
        CostStructureFacade costStructureFacade = (CostStructureFacade) FacadeProvider.getFacade(request, CostStructureFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession.getUser();
        VehiclelinFacade vehicleLineFacade = (VehiclelinFacade) FacadeProvider.getFacade(request, VehiclelinFacade.class);
        Collection<FullEconomicsStruct> colFullEconomicsStruct = null;
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        form.resetForm();
        form.setAltValue2Coll(new Vector<String>());
        Teesf01Fulleconom fullEconomic = (Teesf01Fulleconom) request.getAttribute("fullEconomicSelected");
        Teesc02Coststvers costStrVersion = (Teesc02Coststvers) request.getAttribute("costStrVersion");
        Timestamp econLevel1 = (Timestamp) request.getAttribute("econLevel1");
        String econLevel1Forecasted = (String) request.getAttribute("econLevel1Forecasted");
        Timestamp econLevel2 = (Timestamp) request.getAttribute("econLevel2");
        String econLevel2Forecasted = (String) request.getAttribute("econLevel2Forecasted");
        Map<Teesc03Subcoststr, Collection<Teesc07Subcstitem>> mapaNodosNiveles = (Map<Teesc03Subcoststr, Collection<Teesc07Subcstitem>>) request.getAttribute("mapaNodosNiveles");
        Boolean activacionNiveles;
        if ("true".equalsIgnoreCase((String) request.getAttribute("activacionNiveles")))
        	activacionNiveles = true;
        else
        	activacionNiveles = false;
        form.setMapaNodosNiveles(mapaNodosNiveles);
        if (fullEconomic != null) {
            form.setFullEconomic(fullEconomic);
            form.setFullEconomicDetails();
        } else {
            form.setCostStrVersion(costStrVersion);
            form.setEconLevel1(econLevel1);
            form.setEconLevel1Forecasted(econLevel1Forecasted);
            form.setEconLevel2(econLevel2);
            form.setEconLevel2Forecasted(econLevel2Forecasted);
        }
        MacropartStruct macropartStruct = (MacropartStruct) request
                .getSession().getAttribute("macropartStruct");
        String forward = "success";

        try {
            request.getSession().setAttribute("vehicleLines",vehicleLineFacade.findAllVehiclelin());
            request.getSession().setAttribute("evolveDates",FullEconomicsDateUtil.getComboType());
            request.getSession().setAttribute("economicsTypes",this.getEvolveTypeCombo(user, request));
            // si no hay un full economic en el form viene de costStructure y
            // hay que calcular un nuevo full economic
            if (form.getFullEconomic() == null) {
                colFullEconomicsStruct = fullEconomicsFacade
                        .getFullEconomicsStructCol(costStrVersion
                                .getTeesc01Coststruct().getTeess01Supplier(),
                                costStrVersion.getTeesc03Subcoststr(),
                                macropartStruct.getMacropartPerUnit(),
                                econLevel1, econLevel1Forecasted, econLevel2,
                                econLevel2Forecasted, 1, mapaNodosNiveles, activacionNiveles);
                form.setActivacionNiveles(activacionNiveles);
            } else {// se busca la coleccion correspondiente desde la bbdd
            	mapaNodosNiveles = new HashMap<Teesc03Subcoststr,Collection<Teesc07Subcstitem>>();
                colFullEconomicsStruct = fullEconomicsFacade.getFullEconomicsStructCol(form.getFullEconomic(),mapaNodosNiveles);
//                agregarNodosNiveles(costStructureFacade, form.getFullEconomic().getTeesc02Coststvers().getTeesc03Subcoststr(), mapaNodosNiveles);
                form.setMapaNodosNiveles(mapaNodosNiveles);
            }
            form.setColFullEconomicsStruct(colFullEconomicsStruct);
            this.validateFullEconColl(colFullEconomicsStruct, request);
            form.setTotals(fullEconomicsFacade
                    .calculateTotals(colFullEconomicsStruct));
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            if (e.getArgument() == null)
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
            else
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource(), e.getArgument()));
            saveErrors(request, am);
            if (fullEconomic == null)
                forward = "costStr";

        }
        return mapping.findForward(forward);
    }
    
    public void agregarNodosNiveles(CostStructureFacade costStructureFacade, Teesc03Subcoststr nodoNivel, Map<Teesc03Subcoststr, Collection<Teesc07Subcstitem>> mapaNodosNiveles) throws FullEconomicsException{
        Collection<Teesc07Subcstitem> items = null;
        if (nodoNivel != null){
        	items = costStructureFacade.findSubCostStructureItems(nodoNivel, true);
        	mapaNodosNiveles.put(nodoNivel, items);//Relaciono el Teesc03 (el "nodoNivel") con sus Teesc07 (los "items").
        	Iterator<Teesc03Subcoststr> it = costStructureFacade.findSubCostStructures(nodoNivel).iterator();//Busco los nodosSubniveles.
        	while (it.hasNext()){
        		agregarNodosNiveles(costStructureFacade, it.next(), mapaNodosNiveles);
        	}
        }
    }

    private void validateFullEconColl(
                                      Collection<FullEconomicsStruct> fullEconStrucCol,
                                      HttpServletRequest request) {
        for (FullEconomicsStruct row : fullEconStrucCol) {
            if (row.getSubCostStructure() != null)
                if (row.getSubStructs() == null) {
                    ActionMessages am = new ActionMessages();
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "fullEconomics.error.incompleteSubCostStrc", row
                                    .getSubCostStructure()
                                    .getEesc03SubcstNameN()));
                    saveErrors(request, am);
                }else{
                    this.validateFullEconColl(row.getSubStructs(), request);
                }
        }
    }

    public ActionForward saveFullEconomic(FordActionMapping mapping,
                                          ActionForm actionForm,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                          WebSession webSession,
                                          ActionMessages msgs,
                                          ActionMessages warns,
                                          ActionMessages errorMsgs) {
        FullEconomicsFacade fullEconomicsFacade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        FullEconomicsForm form = (FullEconomicsForm) actionForm;

        try {
            Teesf01Fulleconom fullEco = null;
            fullEco = fullEconomicsFacade.createFullEconomic(this
                    .getFullEconColForCreate(form, request), user);
            form.setFullEconomic(fullEco);
            form.setFullEconomicDetails();
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward recalculate(FordActionMapping mapping,
                                     ActionForm actionForm,
                                     HttpServletRequest request,
                                     HttpServletResponse response,
                                     WebSession webSession,
                                     ActionMessages msgs, ActionMessages warns,
                                     ActionMessages errorMsgs) {
        FullEconomicsFacade fullEconomicsFacade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        VehiclelinFacade vehiclelinFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);
        Collection<FullEconomicsStruct> colFullEconomicsStruct = null;
        FullEconomicsForm form = (FullEconomicsForm) actionForm;

        MacropartStruct macropartStruct = (MacropartStruct) request
                .getSession().getAttribute("macropartStruct");

      //////////////////////////////////////////////////////////////////////
          
        if (form.getFullEconomic() !=  null)
        {
        	    
        	 try{
        	    colFullEconomicsStruct = fullEconomicsFacade.getFullEconomicsStructCol(form.getFullEconomic(), null);
        		form.setColFullEconomicsStruct(colFullEconomicsStruct);
        		this.validateFullEconColl(colFullEconomicsStruct, request);
        		form.setTotals(fullEconomicsFacade.calculateTotals(colFullEconomicsStruct));
              	System.out.println("way()");
        	 } catch (FullEconomicsException ex){ 
        	     System.out.println("way()" + ex.getMessage());
        	 }
        	 return mapping.findForward("success");
        } 
        ///////////////////////////////////////////////////////////////////////
        
        try {
            if (macropartStruct == null) {
                Ncas012VehicleVw vehiclelin = new Ncas012VehicleVw();
                vehiclelin.setCas012VehicleCodeC(form.getVehicleLineSel());
                vehiclelin = vehiclelinFacade.findVehicleLineByPk(vehiclelin);
                Teesp06Mix mix = new Teesp06Mix();
                mix.setEesp06MixEffectiveDateY(FullEconomicsDateUtil
                        .formatFromCombo(form.getMixDate(), form.getMixYear()));
                macropartStruct = fullEconomicsFacade.buildMacropart(form
                        .getFullEconomic().getTeesc02Coststvers()
                        .getTeesc01Coststruct(), vehiclelin, mix);
            }
            Timestamp econLevel1 = FullEconomicsDateUtil.formatFromCombo(form.getEvolveFromSel(), form.getEvolveFromYear());
            form.setEconLevel1(econLevel1);
            Timestamp econLevel2 = FullEconomicsDateUtil.formatFromCombo(form.getEvolveToSel(), form.getEvolveToYear());
            form.setEconLevel2(econLevel2);
            //"Activacion de niveles" se pasa como "false" al llamar al metodo que hace el calculo
            //Esto es porque no se agrego el checkbox en esta pagina, entonces solamente se puede realizar
            //un recalculo con fechas en general. Si el check estuviese en true no serviria.
            //Ademas a todos los items del mapa les tengo que setear el valor general de las evoluciones.
            //En ese caso se dejaria de utilizar el valor particular, por lo tanto en el form queda en false la activacion de niveles.
            form.setActivacionNiveles(false);
            setEvolves(form, econLevel1, econLevel2);
            
            colFullEconomicsStruct = fullEconomicsFacade
                    .getFullEconomicsStructCol(form.getCostStrVersion()
                            .getTeesc01Coststruct().getTeess01Supplier(), form
                            .getCostStrVersion().getTeesc03Subcoststr(),
                            macropartStruct.getMacropartPerUnit(), econLevel1,
                            form.getEconLevel1Forecasted(), econLevel2, form
                                    .getEconLevel2Forecasted(), 1, form.getMapaNodosNiveles(), form.getActivacionNiveles());
            form.setColFullEconomicsStruct(colFullEconomicsStruct);
            form.setTotals(fullEconomicsFacade
                    .calculateTotals(colFullEconomicsStruct));
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }
    
    private void setEvolves(FullEconomicsForm form, Timestamp evolveFrom, Timestamp evolveTo){
        //Seteo a cada item el valor de las evoluciones generales.
    	Map<Teesc03Subcoststr, Collection<Teesc07Subcstitem>> mapaNodosNiveles = form.getMapaNodosNiveles();
    	Set<Teesc03Subcoststr> nodosNiveles = mapaNodosNiveles.keySet();
    	
    	for (Teesc03Subcoststr nodoNivel : nodosNiveles) {
    		Collection<Teesc07Subcstitem> items = mapaNodosNiveles.get(nodoNivel);
        	for (Teesc07Subcstitem item : items) {
    			item.setEvolveFromYearTemp(form.getEvolveFromYear());
    			item.setEvolveToYearTemp(form.getEvolveToYear());
    			item.setEvolveFromTemp(FullEconomicsDateUtil.getMonthFromComboValue(evolveFrom));
    			item.setEvolveFromTempKey(form.getEvolveFromSel());
    			item.setEvolveToTemp(FullEconomicsDateUtil.getMonthFromComboValue(evolveTo));
    			item.setEvolveToTempKey(form.getEvolveToSel());
        	}
		}
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward calculateAltValues(FordActionMapping mapping,
                                            ActionForm actionForm,
                                            HttpServletRequest request,
                                            HttpServletResponse response,
                                            WebSession webSession,
                                            ActionMessages msgs,
                                            ActionMessages warns,
                                            ActionMessages errorMsgs) {
        FullEconomicsFacade fullEconomicsFacade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        Collection<FullEconomicsStruct> colFullEconomicsStruct = null;
        FullEconomicsForm form = (FullEconomicsForm) actionForm;

        Collection<BigDecimal> altValueCol = new LinkedList<BigDecimal>();
        for (String altValue : form.getAltValue2Coll()) {
            altValueCol.add(new BigDecimal(altValue));
        }
        colFullEconomicsStruct = fullEconomicsFacade.getFullEconomicsStructCol(
                form.getColFullEconomicsStruct(), altValueCol);
        form.setColFullEconomicsStruct(colFullEconomicsStruct);
        form.setTotals(fullEconomicsFacade
                .calculateTotals(colFullEconomicsStruct));

        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward calculateSubFullEconomics(
                                                   FordActionMapping mapping,
                                                   ActionForm actionForm,
                                                   HttpServletRequest request,
                                                   HttpServletResponse response,
                                                   WebSession webSession,
                                                   ActionMessages msgs,
                                                   ActionMessages warns,
                                                   ActionMessages errorMsgs) {
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        FullEconomicsFacade fullEconomicsFacade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        Collection<FullEconomicsStruct> colFullEconomicsStruct = null;
        colFullEconomicsStruct = form.getFullEconomicStructSelected()
                .getSubStructs();
        form.setColFullEconomicsStruct(colFullEconomicsStruct);
        form.setTotals(fullEconomicsFacade
                .calculateTotals(colFullEconomicsStruct));
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward viewMacropartInfo(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        VehiclelinFacade vehicleLineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);

        try {
            Ncas012VehicleVw line = new Ncas012VehicleVw();
            line.setCas012VehicleCodeC(form.getVehicleLineSel());
            request.setAttribute("costStructureVersion", form
                    .getCostStrVersion());
            request.setAttribute("vehicleLine", vehicleLineFacade
                    .findVehicleLineByPk(line));

            Teesp06Mix mix = new Teesp06Mix();
            mix.setEesp06MixEffectiveDateY(FullEconomicsDateUtil
                    .formatFromCombo(form.getMixDate(), form.getMixYear()));
            request.setAttribute("mix", mix);

        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward changeCostStr(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade costStrFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        try {
            Teesc02Coststvers newCostStrVer = costStrFacade
                    .createNewCostStructureVersion(user, form
                            .getCostStrVersion());
            request.setAttribute("costStrVersionSelected", newCostStrVer);

        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward changePpSelected(FordActionMapping mapping,
                                          ActionForm actionForm,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                          WebSession webSession,
                                          ActionMessages msgs,
                                          ActionMessages warns,
                                          ActionMessages errorMsgs) {
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        FullEconomicWrapStruct fullEconomicWrap = new FullEconomicWrapStruct();
        fullEconomicWrap.setSubCostStrVers(form.getCostStrVersion());
        fullEconomicWrap.setEconLevel1(form.getEconLevel1());
        fullEconomicWrap.setEconLevel2(form.getEconLevel2());
        fullEconomicWrap.setEconLevel1Forcasted(form.getEconLevel1Forecasted());
        fullEconomicWrap.setEconLevel2Forcasted(form.getEconLevel2Forecasted());
        fullEconomicWrap.setFullEcomimicsCol(form.getColFullEconomicsStruct());
        fullEconomicWrap.setRowSelected(form.getFullEconomicStructSelected());
        fullEconomicWrap.setMacropart((MacropartStruct) request.getSession()
                .getAttribute("macropartStruct"));
        request.setAttribute("fullEconomicWrap", fullEconomicWrap);

        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward setPpSelected(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        FullEconomicWrapStruct wrap = (FullEconomicWrapStruct) request
                .getAttribute("fullEconomicWrap");
        
        
        if (wrap.getRowSelected().getFe().compareTo(wrap.getRowSelected().getPu())>=1)
        {
        	wrap.getRowSelected().setPp(        
            wrap.getRowSelected().getFe().subtract(
        	wrap.getRowSelected().getFe().subtract(wrap.getRowSelected().getPu()).multiply(wrap.getRowSelected().getPayPolVers()
                        .getEese05PpyverPercentP().divide(
                                new BigDecimal(100))).setScale(5,
                BigDecimal.ROUND_FLOOR)));
        } else
        {
        	wrap.getRowSelected().setPp(wrap.getRowSelected().getFe());	
        }
        //-------------------------------------------------
        /* detectar FE negativo = baja de precio */
        /*
        BigDecimal ppItem;
        if (wrap.getRowSelected().getFe().compareTo(wrap.getRowSelected().getPu())>=1)
        {
            ppItem = struct.getPu().add(
                    feItem.subtract(struct.getPu()).multiply(
                            struct.getPayPolVers()
                                    .getEese05PpyverPercentP().divide(
                                            new BigDecimal(100))));

            wrap.getRowSelected().setPp(        
                    wrap.getRowSelected().getPu().add(
                    		wrap.getRowSelected().getFe().subtract(wrap.getRowSelected().getPu()).multiply(wrap.getRowSelected().getPayPolVers()
                                    .getEese05PpyverPercentP().divide(
                                            new BigDecimal(100))).setScale(5,
                            BigDecimal.ROUND_FLOOR)));
            
            
            
        }else
        {
        	ppItem = feItem;
        	System.out.println("paso por menor a 1");
        }
        
       */ 
        
        
        wrap.getRowSelected().setPpAlt(
                wrap.getRowSelected().getFeAlt().multiply(
                        wrap.getRowSelected().getPayPolVers()
                                .getEese05PpyverPercentP().divide(
                                        new BigDecimal(100))).setScale(5,
                        BigDecimal.ROUND_FLOOR));
        form.setColFullEconomicsStruct(wrap.getFullEcomimicsCol());
        form
                .setTotals(facade.calculateTotals(form
                        .getColFullEconomicsStruct()));
        


        // Si no existe full no debe grabar el cambio de politica en la base de datos.
        if (form.getFullEconomic() != null)
        {
	        try {        
	        	
			      Teesf02Fullecoitm fullEconItem = new Teesf02Fullecoitm();
			      fullEconItem.setTeesf01Fulleconom(form.getFullEconomic());
			      fullEconItem.setEesf02PlantCodeC(form.getFullEconomic().getEesf01PlantCodeC());
			      fullEconItem.setTeesc07Subcstitem(wrap.getRowSelected().getSubCostStrItem());
			      fullEconItem.setTeese05Paypolvers(form.getFullEconomicStructSelected().getPayPolVers() ); // wrap.getRowSelected().getPayPolVers());
	              
			      PersistenceUtil.newTransaction();
	        	  Teesf02Fullecoitm workingCopy = (Teesf02Fullecoitm) new FullEconomicsDao().getObjForUpdate(fullEconItem);
	              Teese05Paypolvers copyTeese05Paypolvers = (Teese05Paypolvers) new FullEconomicsDao().getObjForUpdate(wrap.getRowSelected().getPayPolVers());
	        	  
	              workingCopy.setTeese05Paypolvers(copyTeese05Paypolvers);
	        	  workingCopy.setEesf02PaypolPercentP(wrap.getRowSelected().getPayPolVers().getEese05PpyverPercentP());
	              PersistenceUtil.commitTransaction();
	        } catch (PersistenceException e) {
	            System.out.println("error: \n" + e.getMessage() );
	        }
        }
        

        
        
        
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward propose(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        CostStructureFacade cstFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        try {
            Teesc02Coststvers costStrVers = form.getFullEconomic()
                    .getTeesc02Coststvers();
            boolean allOk = true;
            if (costStrVers.getEesc02CststvProposalUserC() == null) {
                Teesc03Subcoststr incompSubCostStr = cstFacade
                        .getIncompleteSubCostStr(form.getFullEconomic()
                                .getTeesc02Coststvers().getTeesc03Subcoststr());
                if (incompSubCostStr != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "fullEconomics.error.incompleteCostStructure",
                            incompSubCostStr.getEesc03SubcstNameN()));
                    saveErrors(request, am);
                    allOk = false;
                } else {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "fullEconomics.warning.proposeCostStr", costStrVers
                                    .getTeesc01Coststruct()
                                    .getEesc01CststrNumberK().toString()
                                    + "."
                                    + costStrVers
                                            .getEesc02CststvVersionNumberK()
                                            .toString()));
                    saveMessages(request, am);
                }
            }
            if (allOk) {
                facade.proposeFullEconomics(form.getFullEconomic(), user);
                form.getFullEconomic()
                        .setEesf01FulleProposalUserC(user.getId());
                form.getFullEconomic().setEesf01FulleProposalS(
                        new Timestamp(System.currentTimeMillis()));
                form.setFullEconomicDetails();
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approve(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {
        FullEconomicsForm form = (FullEconomicsForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        FullEconomicsFacade facade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);

        try {
            if (facade.isFullEconomicApprovable(form.getFullEconomic(), user)) {
                facade.approveFullEconomics(form.getFullEconomic(), user);
                form.getFullEconomic()
                        .setEesf01FulleApprovalUserC(user.getId());
                form.getFullEconomic().setEesf01FulleApprovalS(
                        new Timestamp(System.currentTimeMillis()));
                form.setFullEconomicDetails();
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            if (e.getArgument() == null)
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
            else
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource(), e.getArgument()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

}
